package mysql

import (
	"day15/api/pkg"
	"gorm.io/gorm"
)

type User struct {
	gorm.Model
	Username string `gorm:"type:varchar(30)"`
	Password string `gorm:"type:varchar(255)"`
	Phone    string `gorm:"type:char(11)"`
	Email    string `gorm:"type:varchar(30)"`
	Avatar   string `gorm:"type:varchar(255)"`
	IdCard   string `gorm:"type:char(18)"`
}

func (u *User) Login(username string, password string) (*User, error) {
	var user User
	err = Db.Where("username = ? ", username).First(&user).Error
	if err != nil {
		return nil, err
	}
	err = pkg.VerifyPassword(password, user.Password)
	if err != nil {
		return nil, err
	}
	return &user, nil
}

// 重置密码

func (u *User) UpdatePwd(phone string, password string) error {
	err = Db.Model(&User{}).Where("phone", phone).Update("password", password).Error
	if err != nil {
		return err
	} else {
		return nil
	}
}

func (u *User) FindPwdById(uid int) (string, error) {
	var user User
	err = Db.Model(&User{}).Where("id", uid).First(&user).Error
	if err != nil {
		return "", err
	}
	return user.Password, nil
}

// 修改密码

func (u *User) UpdatePassword(uid string, password string) error {
	err = Db.Model(&User{}).Where("id", uid).Update("password", password).Error
	if err != nil {
		return err
	} else {
		return nil
	}
}

// 分页

func (u *User) Paginate(page int, pageSize int) ([]User, int64, error) {

	var users []User
	var total int64
	offset := (page - 1) * pageSize
	err = Db.Offset(offset).Limit(pageSize).Find(&users).Error
	if err != nil {
		return nil, 0, err
	}
	err = Db.Model(&User{}).Count(&total).Error
	if err != nil {
		return nil, 0, err
	}
	return users, total, nil
}
